package materials

import (
	"context"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MaterialsAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMaterialsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MaterialsAddLogic {
	return &MaterialsAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MaterialsAddLogic) MaterialsAdd(req *types.MaterialsAddRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)
	//1.原料是否存在
	one, err := l.svcCtx.MaterialsModel.FindOneByNameTypes(l.ctx, req.Name, req.Types)
	switch err {
	case model.ErrNotFound: //不处理
	case nil: //无错误:原料存在
		if one.Types == req.Types {
			resp.Code = http.StatusBadRequest
			resp.Msg = "原料类型已存在"
			return resp, nil
		}
	default: //其他错误
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.录入原料信息
	_, err = l.svcCtx.MaterialsModel.Insert(l.ctx, &model.Materials{
		Name:  req.Name,
		Types: req.Types,
	})
	if err != nil {
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务器内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
